package picturetaker.domain;

import java.net.MalformedURLException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Element;

import sun.misc.BASE64Encoder;
import picturetaker.utility.ApplicationConstants;

public class CameraDomainMapper implements ApplicationConstants {

	public static Camera mapCameraFromXMLElement(Element element)
			throws MalformedURLException {
		String userLogin = new BASE64Encoder().encode((
				element.attribute(USER_ATTRIBUTE).getText().trim() +
				COLON + 
				element.attribute(PASS_ATTRIBUTE).getText().trim()
				).getBytes());
		
		Camera camera = new Camera(new URL(element.attribute(URL_ATTRIBUTE).getText().trim()), 
				element.attribute(NAME_ATTRIBUTE).getText().trim(),
				userLogin);
		if (camera.urlExists() && camera.getCameraName() != null && camera.getCameraName().length() > 0)
			return camera;
		else
			throw new MalformedURLException();
	}

	public static List<Camera> mapCameraListFromResultSet(ResultSet result)
			throws SQLException, MalformedURLException  {
		List<Camera> cameraList = new ArrayList<Camera>();
		while (result.next()) {
			cameraList.add(new Camera(new URL (result.getString("URL")),
					result.getString("NAME"), 
					result.getLong("CAMERA_ID")));
		}
		return cameraList;
	}
}
